const { Server } = require('socket.io')
const Redis = require('ioredis')

// redis发布的api
const clientPublish = new Redis({
    host: '120.79.122.205',
    port: 6379,
    password: 'xdclass.net'
})

//redis订阅api
const clientSubscribe = new Redis({
    host: '120.79.122.205',
    port: 6379,
    password: 'xdclass.net'
})
clientSubscribe.subscribe('chat') //redis订阅频道
const websocket = (server) => {
    const io = new Server(server, {
        cors: {
            origin: ["*"],
        },
        transports: ["polling", "websocket"]
    })

    io.on("connection", (socket) => {
        console.log('socket: ', socket);
        //监听bulletChat事件
        socket.on('bulletChat', (info) => {
            console.log('info: ', info);
            clientPublish.publish('chat', JSON.stringify(info))
        })
    })

    //订阅redis收到消息后，websocket通知客户端
    clientSubscribe.on('message',(channel, message) =>{
        console.log('message: ', message);
        io.emit('message', JSON.parse(message))
    })
}
module.exports = websocket